package com.neusoft.elmboot.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Date;

public class JWTUtil {
    private static final String SECRET_KEY = "JabariSecretKey";
    private static final long EXPIRATION_TIME = 24 * 60 * 60 * 1000; // 24小时

    // 生成Token
    public static String generateToken(String username,String authorities) {
        Algorithm algorithm = Algorithm.HMAC256(SECRET_KEY);
        String token = JWT.create()
                .withSubject(username)
             .withClaim("authorities", authorities) // 存储自定义数据
                .withExpiresAt(new Date(System.currentTimeMillis() + EXPIRATION_TIME))// 设置过期时间
                .sign(algorithm);// 使用算法进行签名
        return token;
    }

    // 解析Token
    public static String getUsernameFromToken(String token) {
        try {
            DecodedJWT jwt = getDecodedJWT(token);
            // String username = jwt.getClaim("username").asString();
            return jwt.getSubject();
        } catch (JWTVerificationException e) {
            // Token验证失败，抛出异常
            throw e;
        }
    }

    public static Claim getClaim(String token,String field) {
        try {
            DecodedJWT jwt = getDecodedJWT(token);
            Claim claim = jwt.getClaim(field);
            return claim;
        } catch (JWTVerificationException e) {
            // Token验证失败，抛出异常
            throw e;
        }
    }

    private static DecodedJWT getDecodedJWT(String token) {
        Algorithm algorithm = Algorithm.HMAC256(SECRET_KEY);
        JWTVerifier verifier = JWT.require(algorithm).build();
        DecodedJWT jwt = verifier.verify(token);
        return jwt;
    }

    // 验证Token
    public static boolean validateToken(String token) {
        try {
            getDecodedJWT(token);
            return true;
        } catch (JWTVerificationException e) {
            // Token验证失败
            return false;
        }
    }
}